jQuery.noConflict();

(function($, PLUGIN_ID) {
    'use strict';
    function readWorkbookFromRemoteFile(url, callback) {
        let xhr = new XMLHttpRequest();
        xhr.open('get', url, true);

        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        xhr.responseType = 'arraybuffer';
        xhr.onload = function (e) {
            if (xhr.status == 200) {
                let data = new Uint8Array(xhr.response)
                let workbook = XLSX.read(data, { type: 'array' });
                if (callback) callback(workbook);
            }
        };
        xhr.send();
    }

    function loadModal(fileInfo) {
        let previewElement;
        jQuery(".file-image-container-gaia").each(function (i, e) {
            let fileName = jQuery(e).children("a:eq(0)").text();
            if (fileName == fileInfo.name && jQuery(e).children("button").length == 0) {
                previewElement = jQuery(e);
                return false;
            }
        });

        if (!previewElement) return;

        let modalId = 'myModal' + fileInfo.fileKey;
        let tabId = 'myTab' + fileInfo.fileKey;
        let tabContentId = 'tab-content' + fileInfo.fileKey;
        let $button = $('<button type="button" class="btn btn-default" data-toggle="modal" data-target="#' + modalId + '"><span class="fa fa-search"></span></button>');

        let myModal =
            '<style type="text/css">td{word-break: keep-all;white-space:nowrap;}</style>' +
            '<div class="modal fade tab-pane active" id="' + modalId + '" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">' +
            '<div class="modal-dialog modal-xl" style="border-radius:5px" role="document">' +
            '<div class="modal-content">' +
            '<div class="modal-header">' +
            '<h5 class="modal-title">' + fileInfo.name + '</h5>' +
            '<button type="button" class="close" data-dismiss="modal" aria-label="Close">' +
            '<span aria-hidden="true">&times;</span>' +
            '</button>' +
            '</div>' +
            '<ul class="nav nav-tabs" id=' + tabId + '>' +
            '</ul>' +
            '<div id=' + tabContentId + ' class="tab-content">' +
            '<div class="d-flex justify-content-center">' +
            '<div class="spinner-border" role="status">' +
            '<span class="sr-only">Loading...</span>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '<div class="modal-footer">' +
            '<button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>';

        previewElement.append($button);

        $('body').prepend(myModal);
        $('#' + modalId).on('shown.bs.modal', function (e) {
            loadRemoteFile(fileInfo);
        })
    }

    function loadRemoteFile(fileInfo) {
        let fileUrl = '/k/v1/file.json?fileKey=' + fileInfo.fileKey;
        readWorkbookFromRemoteFile(fileUrl, function (workbook) {
            readWorkbook(workbook, fileInfo);
        });
    }

    function readWorkbook(workbook, fileInfo) {
        let sheetNames = workbook.SheetNames;
        let navHtml = '';
        let tabHtml = '';
        let myTabId = 'myTab' + fileInfo.fileKey;
        let tabContentId = 'tab-content' + fileInfo.fileKey;

        for (let index = 0; index < sheetNames.length; index++) {
            let sheetName = sheetNames[index];
            let worksheet = workbook.Sheets[sheetName];
            let sheetHtml = XLSX.utils.sheet_to_html(worksheet);

            let tabid = "tab" + fileInfo.fileKey + "-" + index;
            let xlsid = "xlsid" + fileInfo.fileKey + "-" + index;
            let active = index == 0 ? "active" : '';
            navHtml += '<li class="nav-item"><a class="nav-link ' + active + '"  href="#"  data-target="#' + tabid + '" data-toggle="tab">' + sheetName + '</a></li>';
            tabHtml += '<div id="' + tabid + '" class="tab-pane ' + active + '" style="padding:10px;overflow:auto;height:600px" >' +
                '<div id="' + xlsid + '">' + sheetHtml + ' </div></div>';
        }
        jQuery("#" + myTabId).html(navHtml);
        jQuery("#" + tabContentId).html(tabHtml);
        jQuery("#" + tabContentId + ' table').addClass("table table-bordered table-hover");
    }

    function checkXls(file) {
        let reg = /\.xl(s[xmb]|t[xm]|am|s)$/g;
        return reg.test(file);
    }

    kintone.events.on('app.record.detail.show', function (event) {
        let record = event.record;
        for (let index in record) {
            let field = record[index];
            if (field.type === "FILE") {
                let fieldValue = field.value;
                fieldValue.forEach(function (file) {
                    if (checkXls(file.name)) {
                        loadModal(file);
                    }
                })
            }
        }
    });

})(jQuery, kintone.$PLUGIN_ID);